<template>
  <Modal title="修改"
         v-model="modelView"
         :mask-closable="false"
         :fullscreen="false"
         :width="720"
         :closable="false"
         @on-visible-change="changeVisible"
         @on-ok="ok">
    <Form ref="updateForm" :model="formData" :label-width="90" :rules="ruleValidate">
      <Row>
        <Col :span="11">
          <FormItem label="主题名:" prop="topicName">
            <Input v-model="formData.topicName" readonly/>
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col :span="22">
          <FormItem label="说明:" prop="topicDesc">
            <Input type = "textarea" v-model="formData.topicDesc"/>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <div slot="footer">
      <Button type="text" @click="cancel">取消</Button>
      <Button type="primary" :loading="buttonLoading" @click="ok">确定</Button>
    </div>
  </Modal>
</template>

<script>
  import {updateTopic} from "@/api/mqtt/topic"

  export default {
    name: "update",
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      initFormData: {

      }
    },
    data() {
      return {
        modelView: false,
        formData: {},
        ruleValidate: {
          topicName: [
            {required: true, message: '主题名不能为空', trigger: 'blur'}
          ]
        },
        buttonLoading: false
      }
    },
    watch: {
      visible(newVal) {
        this.modelView = newVal
      }
    },
    methods: {
      changeVisible() {
        if (this.modelView){
          this.formData = JSON.parse(JSON.stringify(this.initFormData))
        } else {
          this.formData = {}
        }
        this.$emit('update:visible', this.modelView)
      },
      cancel() {
        this.modelView = false
      },
      ok() {
        const self = this
        self.$refs['updateForm'].validate((valid) => {
          self.buttonLoading = true
          let newData = JSON.parse(JSON.stringify(self.formData))
          updateTopic(newData)
            .then(response => {
              self.buttonLoading = false
              self.modelView = false
              self.$Message.success({
                content: '修改成功'
              })
              self.$emit('on-ok', newData)
            })
            .catch((err) => {
              self.isLoading = false
              self.$Message.error({
                content: err,
                duration: 10,
                closable: true
              })
            })
        })
      }
    }
  }
</script>

<style scoped>

</style>
